﻿using System;
using Reactor.Environment;
using Reactor.ServiceGrid;

namespace Reactor.Entities
{
    public abstract class ServiceEntityBase
    {
        private TimeSpan? _intervalExpiration;

        public ServiceIdentifier Identifier { get; set; }

        public DateTime LastSeen { get; set; }

        public virtual bool IsOnline
        {
            get
            {
                if (!_intervalExpiration.HasValue)
                    GetHealthIntervalExpirationValue();

                // ReSharper disable PossibleInvalidOperationException
                return (DateTime.Now - LastSeen) < _intervalExpiration.Value;
                // ReSharper restore PossibleInvalidOperationException
            }
        }

        private void GetHealthIntervalExpirationValue()
        {
            int intervalInMinutes;
            if (!int.TryParse(Context.Configuration.GetConfigurationValue("Global.ServiceHealthIntervalExpiration"), out intervalInMinutes))
                intervalInMinutes = 5;

            _intervalExpiration = new TimeSpan(0, intervalInMinutes, 0);
        }
    }
}
